package com.ruoyi.web.controller.fx;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.fx.FxGoodclassify;
import com.ruoyi.system.mapper.fx.FxGoodclassifyMapper;
import com.ruoyi.system.service.fx.IFxGoodclassifyService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品分类Controller
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@RestController
@RequestMapping("/fx/goodclassify")
public class FxGoodclassifyController extends BaseController {
    @Autowired
    private IFxGoodclassifyService fxGoodclassifyService;

    @Autowired
    private FxGoodclassifyMapper fxGoodclassifyMapper;

    /**
     * 查询商品分类列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FxGoodclassify fxGoodclassify) {
        List<FxGoodclassify> list = fxGoodclassifyService.selectFxGoodclassifyList(fxGoodclassify);
        return getDataTable(list);
    }

    @GetMapping("/list/exclude/{id}")
    public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id) {
        List<FxGoodclassify> list = fxGoodclassifyService.selectFxGoodclassifyList(new FxGoodclassify());
        list.removeIf(d -> d.getId().intValue() == id || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), id + ""));
        return success(list);
    }

    /**
     * 导出商品分类列表
     */
    @Log(title = "商品分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FxGoodclassify fxGoodclassify) {
        List<FxGoodclassify> list = fxGoodclassifyService.selectFxGoodclassifyList(fxGoodclassify);
        ExcelUtil<FxGoodclassify> util = new ExcelUtil<FxGoodclassify>(FxGoodclassify.class);
        util.exportExcel(response, list, "商品分类数据");
    }

    /**
     * 导入商品分类列表
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "商品分类导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) {
        fxGoodclassifyService.importData(file);
        return success();
    }

    /**
     * 获取商品分类详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(fxGoodclassifyService.selectFxGoodclassifyById(id));
    }

    /**
     * 新增商品分类
     */
    @Log(title = "商品分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Valid FxGoodclassify fxGoodclassify) {
        // 判断当前新增 名称是否唯一
        if (!fxGoodclassifyService.checkNameUnique(fxGoodclassify)) {
            return error("新增分类 '" + fxGoodclassify.getDeptName() + "' 失败，分类名称已存在");
        }
        fxGoodclassify.setCreateBy(getUsername());
        return toAjax(fxGoodclassifyService.insertFxGoodclassify(fxGoodclassify));
    }

    /**
     * 修改商品分类
     */
    @Log(title = "商品分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FxGoodclassify fxGoodclassify) {
        Long id = fxGoodclassify.getId();
        if (!fxGoodclassifyService.checkNameUnique(fxGoodclassify)) {
            return error("修改分类 '" + fxGoodclassify.getDeptName() + "' 失败，分类名称已存在");
        } else if (fxGoodclassify.getParentId().equals(id)) {
            return error("修改分类'" + fxGoodclassify.getDeptName() + "'失败，上级分类不能是自己");
        } else if (1 == fxGoodclassify.getStatus() && fxGoodclassifyService.checkAllChildNodeStatusById(id) > 0) {
            return error("该分类包含未停用的子分类！");
        }
        fxGoodclassify.setUpdateBy(getUsername());
        return toAjax(fxGoodclassifyService.updateFxGoodclassify(fxGoodclassify));
    }

    /**
     * 删除商品分类
     */
    @Log(title = "商品分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fxGoodclassifyService.deleteFxGoodclassifyByIds(ids));
    }

    @GetMapping("/listTree")
    public TableDataInfo listTree(FxGoodclassify fxGoodclassify) {
        List<FxGoodclassify> goodList = fxGoodclassifyService.selectFxGoodclassifyList(fxGoodclassify);
        startPage();
        List<FxGoodclassify> list = fxGoodclassifyService.selectGoodClassTree(fxGoodclassify, goodList);
        return getDataTable(list);
    }


    @GetMapping("/Class")
    public AjaxResult get() {
        Path startPath = Paths.get("D:\\Download\\图片");
        try {
            // 或者收集到一个List中
            List<Path> allFiles = Files.walk(startPath)
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());

            // 转换成 URL 前缀
            String baseUrl = "/profile/categoryImg";

            // 替换文件路径中的 "D:\\Download\\图片" 前缀为 URL 前缀
            String localPathPrefix = "D:\\Download\\图片";


            for (Path allFile : allFiles) {
                // 获取父目录的名称
                String parentDirectory = allFile.getParent().getFileName().toString();

                // 使用正则表达式去掉前面的数字和空格
                parentDirectory = parentDirectory.replaceAll("^[0-9\\.\\s]+", "");

                // 获取文件名称（不带扩展名）
                String fileName = allFile.getFileName().toString();
                fileName = fileName.substring(0, fileName.lastIndexOf(".")); // 去掉扩展名

                List<FxGoodclassify> fxGoodclassify = fxGoodclassifyMapper.selectName(parentDirectory, fileName);
                for (FxGoodclassify goodclassify : fxGoodclassify) {
                    if (goodclassify != null) {
                        if (!goodclassify.getId().equals(1252L) && !goodclassify.getId().equals(1261L)) {
                            // 将路径转换成 URL
                            String finalUrl = convertToUrl(allFile, localPathPrefix, baseUrl);
                            fxGoodclassifyMapper.updateUrl(goodclassify.getId(), finalUrl);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success("图片上传成功");
    }

    // 将本地文件路径转换成 URL
    public static String convertToUrl(Path filePath, String localPathPrefix, String baseUrl) {
        // 移除本地前缀，并替换为 URL 前缀
        String relativePath = filePath.toString().replace(localPathPrefix, "");

        // 替换所有 Windows 路径中的反斜杠为 URL 中的正斜杠
        relativePath = relativePath.replace("\\", "/");

        // 拼接完整的 URL
        return baseUrl + relativePath;
    }

}
